﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using DIBestPractice.Domain;

namespace DIBestPractice.Repository.Store
{
    public class InMemoryDbStore<TAggregate> : IDBStore<TAggregate> where TAggregate:AggregateRoot
    {
        private static  ConcurrentDictionary<Type,List<TAggregate>> _store=new ConcurrentDictionary<Type, List<TAggregate>>();

        public TAggregate Get(Guid id)
        {
            var list = _store[typeof(TAggregate)];
            return list.Single(x => x.Id == id);
        }

        public void Save(TAggregate aggregate)
        {
            List<TAggregate> list;
            if(!_store.TryGetValue(typeof(TAggregate),out list))
            {
                _store[typeof(TAggregate)]=new List<TAggregate>();
            }

            _store[typeof(TAggregate)].Add(aggregate);
        }

        public void Remove(Guid id)
        {
            var list = _store[typeof(TAggregate)];
            list.Remove(list.Single(x => x.Id == id));
        }

        public List<TAggregate> GetAll()
        {
            return _store[typeof(TAggregate)];
        }
    }
}